import Page from "@/components/page"
import UiButton from "@/components/ui/UiButton";
import UiForm, { UiFormItem, UiFormSubmit } from "@/components/ui/UiForm";
import UiInput from "@/components/ui/UiInput";
import { openInformationModal } from "@/components/ui/UiModal";
import useViewer from "@/hooks/useViewer"
import { gqlError } from "@/libs/apollo-error";
import { gql, useMutation } from "@apollo/client";
import { useCallback } from "react";

const UpdPwdMutation = gql`
    mutation UpdPwd(
        $pwd:String!,
        $before:String!
    ){
        updPwd(pwd:$pwd,before:$before){
            id
        }
    }
`
const HomePage = () => {
    const { data } = useViewer();
    const [upd] = useMutation(UpdPwdMutation, {
        onCompleted() {
            window.location.reload()
        },
        onError(error, clientOptions) {
            gqlError(error)
        },
    })

    const onSubmit = useCallback(({
        pwd,
        newPwd,
        confirmPwd
    }: any) => {
        if (newPwd !== confirmPwd) {
            return openInformationModal(() => ({ title: "两次密码不一致" }))
        }
        if (newPwd.length < 6) {
            return openInformationModal(() => ({ title: "密码不得小于6位" }))
        }
        upd({
            variables: {
                pwd: newPwd,
                before: pwd
            }
        })
    }, [])
    return (
        <Page>
            <div className="card w-96 bg-base-100 shadow-xl">
                <div className="card-body">
                    <h2 className="card-title">{data?.name}</h2>
                    <UiForm
                        onSubmit={onSubmit}
                    >
                        <UiFormItem
                            label="原密码"
                            name="pwd"
                        >
                            <UiInput />
                        </UiFormItem>
                        <UiFormItem
                            label="新密码"
                            name="newPwd"
                        >
                            <UiInput />
                        </UiFormItem>
                        <UiFormItem
                            label="确认密码"
                            name="confirmPwd"
                        >
                            <UiInput />
                        </UiFormItem>
                        <UiFormSubmit>
                            <UiButton submit>修改密码</UiButton>
                        </UiFormSubmit>
                    </UiForm>
                </div>
            </div>
        </Page>
    )
}
export default HomePage